package com.tarena.lbs.content.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.content.dao.mapper.ArticleMapper;
import com.tarena.lbs.content.dao.repository.ArticleESRepository;
import com.tarena.lbs.content.dao.repository.ArticleRepository;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.po.ArticleSearchPO;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Repository
public class ArticleRepositoryImpl implements ArticleRepository {
    @Autowired
    private ArticleESRepository articleESRepository;
    @Autowired
    private final ElasticsearchOperations elasticsearchOperations; // 需要注入
    @Autowired
    private ArticleMapper articleMapper;

    public ArticleRepositoryImpl(ArticleESRepository articleESRepository,
                                 ElasticsearchOperations elasticsearchOperations) {
        this.articleESRepository = articleESRepository;
        this.elasticsearchOperations = elasticsearchOperations;
    }

    @Override
    public PageInfo<ArticleSearchPO> pageList(ArticleQuery query) {
        // 1. 构建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 标题模糊匹配
        if (StringUtils.isNotBlank(query.getArticleTitle())) {
            boolQuery.must(QueryBuilders.matchQuery("articleTitle", query.getArticleTitle()));
        }

        // 分类ID精确匹配
        if (query.getArticleCategoryId() != null) {
            boolQuery.must(QueryBuilders.termQuery("articleCategoryId", query.getArticleCategoryId()));
        }

        // 状态多值查询
        if (query.getArticleStatus() != null && !query.getArticleStatus().isEmpty()) {
            boolQuery.must(QueryBuilders.termsQuery("articleStatus", query.getArticleStatus()));
        }

        // 活动ID精确匹配
        if (query.getActivityId() != null) {
            boolQuery.must(QueryBuilders.termQuery("activityId", query.getActivityId()));
        }

        // 时间范围查询
        if (query.getUpdateStartTime() != null || query.getUpdateEndTime() != null) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("updateTime");
            if (query.getUpdateStartTime() != null) {
                rangeQuery.gte(query.getUpdateStartTime().getTime());
            }
            if (query.getUpdateEndTime() != null) {
                rangeQuery.lte(query.getUpdateEndTime().getTime());
            }
            boolQuery.must(rangeQuery);
        }

        // 2. 创建分页参数（Spring Data分页从0开始）
        int pageNo = query.getPageNo() != null ? query.getPageNo() - 1 : 0;
        int pageSize = query.getPageSize() != null ? query.getPageSize() : 10;
        Pageable pageable = PageRequest.of(pageNo, pageSize);

        // 3. 构建完整查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQuery)
                .withPageable(pageable)
                .build();

        // 4. 执行ES查询
        SearchHits<ArticleSearchPO> searchHits = elasticsearchOperations.search(
                searchQuery,
                ArticleSearchPO.class
        );

        // 5. 获取查询结果
        List<ArticleSearchPO> content = new ArrayList<>();
        for (org.springframework.data.elasticsearch.core.SearchHit<ArticleSearchPO> hit : searchHits) {
            content.add(hit.getContent());
        }
        return new PageInfo<>(content);
    }

    @Override
    public void addArticle(ArticleContentParam param) {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        String username;
        if (userPrinciple == null) {
            throw new RuntimeException("用户未登录");
        }else {
            username = userPrinciple.getNickname();
        }
        ArticleSearchPO articleSearchPO = new ArticleSearchPO();
        BeanUtils.copyProperties(param,articleSearchPO);
        articleSearchPO.setCreateTime(new Date());
        articleSearchPO.setArticleUsername(username);
        articleESRepository.save(articleSearchPO);
    }

    @Override
    public Set<String> SetArticle(ArticleQuery articleQuery) {



        return null;
    }
}